using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Excel;
using Admin.NET.Application.Service.Report.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;

namespace Admin.NET.Application.Service.Report;

[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class EnergycontrastService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<PowerConsumptionRecord> _rep;

	private readonly SqlSugarRepository<ElectricMeter> _repQuery;

	public EnergycontrastService(SqlSugarRepository<PowerConsumptionRecord> rep, SqlSugarRepository<ElectricMeter> repQuery)
	{
		_rep = rep;
		_repQuery = repQuery;
	}

	[HttpPost("/report/getenergycontrast")]
	public async Task<List<EneryReport>> GetEnergycontrast([FromBody] EneryInput input)
	{
		new List<EneryReport>();
		List<MeterAllValue> lastValue = new List<MeterAllValue>();
		List<MeterAllValue> nowValue = new List<MeterAllValue>();
		new List<PowerMeter>();
		List<MeterInfo> meterAllInfo = await (from u in _repQuery.Context.Queryable<ElectricMeter>()
			where input.Ids.Contains(u.Id) && u.IsDelete == false
			select new MeterInfo
			{
				MeterNo = u.Sn,
				Id = u.Id,
				Name = u.Name
			}).ToListAsync();
		if (input.Type == 0)
		{
			DateTime starttime = input.Time.Date.AddDays(-1.0);
			DateTime endtime = input.Time.Date.AddDays(1.0);
			List<PowerMeter> result = await (from u in _rep.Context.Queryable<PowerConsumptionRecord>()
				where input.Ids.Contains(u.MeterId) && u.CreateTime >= starttime && u.CreateTime < endtime
				select new PowerMeter
				{
					CreateTime = u.CreateTime,
					MeterId = u.MeterId,
					Name = u.Name,
					CombinedActiveTotalElectricEnergyDifference = u.CombinedActiveTotalElectricEnergyDifference
				}).ToListAsync();
			nowValue = (from u in result
				where u.CreateTime >= input.Time.Date
				group u by new { u.MeterId } into u
				select new MeterAllValue
				{
					Id = u.Key.MeterId,
					AllCount = u.Sum((PowerMeter u) => u.CombinedActiveTotalElectricEnergyDifference)
				}).ToList();
			if (input.Time.Date == DateTime.Now.Date)
			{
				DateTime lastTimeNow = DateTime.Now.AddDays(-1.0);
				lastValue = (from u in result
					where u.CreateTime <= lastTimeNow
					group u by new { u.MeterId } into u
					select new MeterAllValue
					{
						Id = u.Key.MeterId,
						AllCount = u.Sum((PowerMeter u) => u.CombinedActiveTotalElectricEnergyDifference)
					}).ToList();
			}
			else
			{
				DateTime lastTimeNow = DateTime.Now.Date;
				lastValue = (from u in result
					where u.CreateTime <= lastTimeNow
					group u by new { u.MeterId } into u
					select new MeterAllValue
					{
						Id = u.Key.MeterId,
						AllCount = u.Sum((PowerMeter u) => u.CombinedActiveTotalElectricEnergyDifference)
					}).ToList();
			}
		}
		else
		{
			DateTime timeNow = new DateTime(input.Time.Year, input.Time.Month, 1);
			DateTime starttime = timeNow.AddMonths(-1);
			DateTime endtime = timeNow.AddMonths(1);
			List<PowerMeter> result = await (from u in _rep.Context.Queryable<PowerConsumptionRecord>()
				where input.Ids.Contains(u.MeterId) && u.CreateTime >= starttime && u.CreateTime < endtime
				select new PowerMeter
				{
					CreateTime = u.CreateTime,
					MeterId = u.MeterId,
					Name = u.Name,
					CombinedActiveTotalElectricEnergyDifference = u.CombinedActiveTotalElectricEnergyDifference
				}).ToListAsync();
			nowValue = (from u in result
				where u.CreateTime >= timeNow
				group u by new { u.MeterId } into u
				select new MeterAllValue
				{
					Id = u.Key.MeterId,
					AllCount = u.Sum((PowerMeter u) => u.CombinedActiveTotalElectricEnergyDifference)
				}).ToList();
			if (input.Time.Year == DateTime.Now.Year && input.Time.Month == DateTime.Now.Month)
			{
				DateTime lastTimeNow = DateTime.Now.Date.AddMonths(-1);
				lastValue = (from u in result
					where u.CreateTime <= lastTimeNow
					group u by new { u.MeterId } into u
					select new MeterAllValue
					{
						Id = u.Key.MeterId,
						AllCount = u.Sum((PowerMeter u) => u.CombinedActiveTotalElectricEnergyDifference)
					}).ToList();
			}
			else
			{
				DateTime lastTimeNow = timeNow;
				lastValue = (from u in result
					where u.CreateTime < lastTimeNow
					group u by new { u.MeterId } into u
					select new MeterAllValue
					{
						Id = u.Key.MeterId,
						AllCount = u.Sum((PowerMeter u) => u.CombinedActiveTotalElectricEnergyDifference)
					}).ToList();
			}
		}
		List<EneryReport> list = meterAllInfo.Select((MeterInfo u) => new EneryReport
		{
			MeterName = (from s in meterAllInfo
				where s.Id == u.Id
				select s.Name).FirstOrDefault(),
			NowPower = ((from s in nowValue
				where s.Id == u.Id
				select s into u
				select u.AllCount).FirstOrDefault().ToString() ?? ""),
			LastPower = ((from s in lastValue
				where s.Id == u.Id
				select s into u
				select u.AllCount).FirstOrDefault().ToString() ?? ""),
			MeterNo = (from s in meterAllInfo
				where s.Id == u.Id
				select s.MeterNo).FirstOrDefault()
		}).ToList();
		return list.OrderByDescending((EneryReport u) => u.NowPower).ToList();
	}

	[HttpPost("/report/getenergycontrastexecl")]
	public async Task<IActionResult> ExportEnergycontrast([FromBody] EneryInput input)
	{
		List<EneryReport> list = await GetEnergycontrast(input);
		string str = "能耗环比-" + DateTime.Now.ToString("yyyy-MM-dd");
		List<string> column = new List<string>();
		string titleEx = "能耗环比-";
		List<string> title = new List<string>();
		string now;
		string lasts;
		if (input.Type == 0)
		{
			now = "当日";
			lasts = "昨日";
			titleEx += input.Time.ToString("yyyy-MM-dd");
		}
		else
		{
			now = "当月";
			lasts = "上月";
			titleEx += input.Time.ToString("yyyy-MM");
		}
		column.AddRange(new string[7] { "MeterNo", "MeterName", "NowPower", "LastPower", "AddPower", "AddCo2", "Specific" });
		title.AddRange(new string[7]
		{
			"表号",
			"名称",
			now + "电能（kW.h）",
			lasts + "昨日电能（kg）",
			"节约能耗（kW.h）",
			"能耗环比（%）",
			"节约碳排放（kg）"
		});
		MemoryStream memery = ExportToExcel.ExportToList(list.ToArray(), titleEx, titleEx, column.ToArray(), title.ToArray());
		byte[] aa = memery.ToArray();
		return new FileStreamResult(new MemoryStream(aa), "application/octet-stream")
		{
			FileDownloadName = str + ".xlsx"
		};
	}
}
